Categories
Day.js

Manipulating Dates with Day.js — Get the Time Relative to a Date

Spread the love

Day.js is a JavaScript library that lets us manipulate dates in our apps.

In this article, we’ll look at how to use Day.js to manipulate dates in our JavaScript apps.

Get the Time to Now

We can get the string of the relative time to now with the toNow method available with the relativeTime plugin.

For instance, we can write:

const dayjs = require("dayjs");
const relativeTime = require("dayjs/plugin/relativeTime");
dayjs.extend(relativeTime);

const result = dayjs("1999-01-01").toNow();
console.log(result);

to get how long from January 1, 1999 until we reach today’s date.

Therefore, result is 'in 23 years‘ in 2021.

We can also pass in true to toNow to remove the suffix.

And we’ll get '23 years' for result .

Get the Time Until We Reach the Given Time

We can get the string of the relative time to now with the to method available with the relativeTime plugin.

For instance, we can write:

const dayjs = require("dayjs");
const relativeTime = require("dayjs/plugin/relativeTime");
dayjs.extend(relativeTime);

const a = dayjs("2020-01-01");
const result = dayjs("1999-01-01").to(a);
console.log(result);

to get how long from January 1, 1999 until we reach January 1, 2020

Therefore, result is 'in 21 years‘

We can also pass in true to to as its 2nd argument to remove the suffix.

And we’ll get '21 years' for result .

Conclusion

Day.js is a JavaScript library that lets us manipulate dates in our apps.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *